//
//  CJMainTabBar.swift
//  SinaWeibo
//
//  Created by 程建 on 16/9/22.
//  Copyright © 2016年 itcast. All rights reserved.
//

import UIKit

class CJMainTabBar: UITabBar {

    //定义一个闭包
    var composeClosure: (()->())?
    
    //外界可以通过手写代码的方式创建tabBar
    override init(frame: CGRect) {
        super.init(frame: frame)
        //添加撰写按钮
        addSubview(composeBtn)
        
        //实现中间按钮的点击方法
        composeBtn.addTarget(self, action: #selector(composeBtnDidClick), for: UIControlEvents.touchUpInside)
        
    }
    
    
   @objc private func composeBtnDidClick() {
        
        composeClosure?()
    
    }
    
    
    //解档 当视图从xib或者 sb中加载的时候会执行这个代码
    //从xib加载程序会崩溃
    required init?(coder aDecoder: NSCoder) {
        //默认实现报错
        fatalError("init(coder:) has not been implemented")
    }
    
    
    
    //注意这里一定要super
    override func layoutSubviews() {
        super.layoutSubviews()
        
        let btnW = UIScreen.main.bounds.width / 5
        let btnH = self.bounds.height
        
        //定义递增索引
        var index = 0
        //遍历子视图的位置
        for subview in subviews{
            //判断是否是UITabBarButton
            if subview.isKind(of: NSClassFromString("UITabBarButton")!) {
                
                
                
                subview.frame = CGRect(x: btnW * CGFloat(index), y: 0, width: btnW, height: btnH)
                
                //这里判断index是否等于1 如果等于时,这时index就需要加上二,否则加一
/*
                 if index == 1 {
                    index+=1
                }
                index+=1
*/
                //换种写法
                index += (index == 1) ? 2:1
                
            }
        }
        //设置撰写按钮的frame
        composeBtn.bounds.size = CGSize(width: btnW, height: btnH)
        composeBtn.center = CGPoint(x: self.center.x, y: self.bounds.height * 0.5)
        
    }
    
    //需要通过懒加载实例化撰写微博的按钮
   private lazy var composeBtn: UIButton = {
        
        let btn = UIButton()
        
        //设置图片
        btn.setImage(#imageLiteral(resourceName: "tabbar_compose_icon_add"), for: UIControlState.normal)
        btn.setImage(#imageLiteral(resourceName: "tabbar_compose_icon_add_highlighted"), for: UIControlState.highlighted)
    
        //设置背景颜色
        btn.setBackgroundImage(#imageLiteral(resourceName: "tabbar_compose_button"), for: UIControlState.normal)
        btn.setBackgroundImage(#imageLiteral(resourceName: "tabbar_compose_button_highlighted"), for: UIControlState.highlighted)
        
        return btn
        
    }()
    
    
}
